# 通过某个关键字排序一个字典列表
from operator import itemgetter

rows = [
    {'fname':'Brian', 'lname':'Jones','uid':1003},
    {'fname':'David', 'lname':'Beazley','uid':1002},
    {'fname':'Cohn', 'lname':'Aeazley','uid':1002},
    {'fname':'Cohn', 'lname':'Cleese','uid':1001},
    {'fname':'Aig', 'lname':'Jones','uid':1004},
]

def demo_1():
    # itemgetter方法可以根据固定字段排序
    rows_by_fname = sorted(rows, key=itemgetter('fname'))
    rows_by_uid = sorted(rows, key=itemgetter('uid'))
    print(rows_by_fname)
    print(rows_by_uid)
    rows_by_fname_lname = sorted(rows, key=itemgetter('fname', 'lname'))
    print(rows_by_fname_lname)

def demo_2():
    # lambda可以代替itemgetter方法，但是后者效率更高
    rows_by_fname = sorted(rows, key = lambda r : r['fname'])
    rows_by_lfname = sorted(rows, key=lambda r : (r['fname'],r['lname']))
    print(rows_by_fname)
    print(rows_by_lfname)


if __name__ == '__main__':
    demo_1()
    demo_2()